package com.ajavaer.framework.common.tools;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ServletTools {

    public static Object getSession(HttpServletRequest request, String sessionKey) {
        return request.getSession().getAttribute(sessionKey);
    }

    public static void setSessionAttribute(HttpServletRequest request, String sessionKey, Object sessionObject) {
        request.getSession().setMaxInactiveInterval(120 * 60);
        request.getSession().setAttribute(sessionKey, sessionObject);
    }

    public static void printString(HttpServletResponse response, String message) {
        response.setContentType("text/plain; charset=utf-8");
        printWriter(response, message);
    }

    public static ServletOutputStream printExcel(HttpServletResponse response, String fileName) throws IOException {
        response.setCharacterEncoding("GBK");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
        return response.getOutputStream();
    }


    public static void printJson(HttpServletResponse response, String message) {
        response.setContentType("application/json; charset=utf-8");
        printWriter(response, message);
    }

    public static void printObjJson(HttpServletResponse response, Object message) {
        response.setContentType("application/json; charset=utf-8");
        printWriter(response, JsonTools.beanToJson(message));
    }

    public static void printHtml(HttpServletResponse response, String message) {
        response.setContentType("application/html; charset=utf-8");
        printWriter(response, message);
    }

    public static void printWriter(HttpServletResponse response, String message) {
        try {
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.print(message);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeImage(HttpServletResponse response, BufferedImage buffImg, String imageExt) {
        ServletOutputStream sos = null;
        try {
            sos = response.getOutputStream();
            ImageIO.write(buffImg, imageExt, sos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (sos != null) {
                    sos.flush();
                    sos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }

    public static String getRequestBody(HttpServletRequest request) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

}
